package com.piece.admin.event;

import com.piece.admin.model.TbSysUser;
import com.piece.core.framework.constant.ApplicationConstants;
import com.piece.core.framework.enums.OptionType;
import com.piece.core.framework.util.string.JsonUtil;
import com.piece.core.framework.properties.ApplicationProperties;
import com.piece.core.mongo.entity.MongoMessage;
import com.piece.core.mongo.service.MongoMessageService;
import com.piece.core.web.util.MailUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

/**
 * 系统操作服务
 */
@Slf4j
@Service
public class SystemOperatorEvent {

    @Value("${spring.application.name:#{null}}")
    private String applicationName;

    @Autowired
    private ApplicationProperties applicationProperties;

    @Autowired
    private ApplicationContext applicationContext;

    @Resource
    private MongoMessageService mongoMessageService;

    /**
     * 注册监听事件
     */
    public void onRegisterEvent(TbSysUser user, int action) {
        SystemPostEvent event = new SystemPostEvent(System.currentTimeMillis());
        event.setUser(user);
        event.setAction(action);
        applicationContext.publishEvent(event);
    }

    public void registerMessage(String json) {
        try {
            TbSysUser user = JsonUtil.toBean(json, TbSysUser.class);
            String title = "恭喜你！【" + user.getLoginName() + "】注册用户成功，欢迎加入【" + applicationName + "】！";
            MongoMessage message = new MongoMessage();
            message.setTitle(title);
            message.setType(OptionType.MESSAGE.getCode());
            message.setReceiver(user.getUserId().toString());
            message = mongoMessageService.insert(message);
            message.setRouter("piece-admin/api/message/read/" + message.getId());
            mongoMessageService.update(message);
        } catch (Exception e) {
            log.error("注册用户信息异常：{}", e.getMessage());
        }
    }

    public void registerConfirmMessage(String json) {
        try {
            TbSysUser user = JsonUtil.toBean(json, TbSysUser.class);
            String title = "【" + applicationName + "】用户注册确认！";
            String href = "<a href=\"" + applicationProperties.getValue(ApplicationConstants.SYSTEM_ADDRESS) + "\" target=\"_blank\">确认注册</a>";
            String content = "【" + user.getLoginName() + "】您好，请点击访问：" + href + "，进入【" + applicationName + "】！";
            MailUtil.getInstance().sendHtmlMail(user.getEmail(), title, content);
        } catch (Exception e) {
            log.error("注册用户确认信息异常：{}", e.getMessage());
        }
    }
}
